package com.fastdfs.proto.storage;


import com.itextpdf.text.DocumentException;
import com.itextpdf.text.exceptions.BadPasswordException;
import com.itextpdf.text.pdf.PdfReader;
import css.sword.util.Doc2Docx;
import css.sword.util.PdfUtils;
import css.sword.util.WpsSecureUtil;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.xdocreport.utils.StringUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


public class DownloadStream implements DownloadCallback<Integer>
{

    Logger log= LoggerFactory.getLogger(DownloadStream.class);
	private OutputStream out;
	private String waterMark;
	private long currentBytes = 0;
	private boolean convertDocx=false;
	private String wordWaterMark;
	private HttpServletResponse response;
	private String caToken;
	private boolean isWpsSecure;
	private boolean packageDownload;

	public DownloadStream(OutputStream out, String waterMark, boolean convertDocx, String wordWaterMark, HttpServletResponse response,String caToken,boolean isWpsSecure,boolean packageDownload)
	{
		super();
		this.out = out;
		this.waterMark = waterMark;
		this.convertDocx=convertDocx;
		this.wordWaterMark=wordWaterMark;
		this.response=response;
		this.caToken=caToken;
		this.isWpsSecure=isWpsSecure;
		this.packageDownload=packageDownload;
	}
    @Override
	public Integer recv(InputStream ins)
	{
		InputStream in = null;
		try {
			in = new BufferedInputStream(ins);
			// 通过ioutil 对接输入输出流，实现文件下载
			//IOUtils.copy(in, out);
            log.info("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"+wordWaterMark);
			if(isWpsSecure&&StringUtils.isNotEmpty(caToken)){
                log.info("yyyyyyyyyyyyyyyyyyyyyyyy"+caToken+isWpsSecure);
				String tempFile =
						System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + ".docx";
				FileOutputStream fileIn = new FileOutputStream(tempFile);

				IOUtils.copy(in, fileIn);
				fileIn.flush();
				fileIn.close();
				String destFile =
						System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + ".wpss";
				WpsSecureUtil.createSecurityDoc(tempFile,destFile,caToken);
				response.setContentLength((int)new File(tempFile).length());
				System.out.println("Content-Length"+(int)new File(destFile).length()+"");
				response.addHeader("Content-Length", (int)new File(destFile).length()+"");
				IOUtils.copy(new FileInputStream(destFile),out);

				return 0;
			}

            log.info("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"+wordWaterMark);
			if(StringUtils.isEmpty(waterMark)){
				if(StringUtils.isEmpty(wordWaterMark)) {
					if (!convertDocx){
						IOUtils.copy(in, out);
                        //log.info("zzzzzzzzzzzzzzzzzzzzz");
						return 0;
					}
					else {
//					String tempFile =
//							System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + ".doc";
//					FileOutputStream fileIn = new FileOutputStream(tempFile);
//					// 通过ioutil 对接输入输出流，实现文件下载
//					IOUtils.copy(in, fileIn);
//					fileIn.flush();
//					fileIn.close();
						//Doc2Docx.doc2docx(tempFile,tempFile+"x");
					Doc2Docx.convertDocToDocx(in, out);
//
//					IOUtils.copy(new FileInputStream(tempFile+"x"),out );
//					new File(tempFile+"x").delete();
//					new File(tempFile).delete();
					}
				}else{
					String tempFile =
							System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + ".docx";
					FileOutputStream fileIn = new FileOutputStream(tempFile);

					IOUtils.copy(in, fileIn);
					fileIn.flush();
					fileIn.close();
					PdfUtils.addWaterMark(tempFile,wordWaterMark);

					response.addHeader("Content-Length", (int)new File(tempFile).length()+"");
					System.out.println("Content-Lengtheeeeeeeeeeeeeeeeeeeeeeeeeeee"+(int)new File(tempFile).length()+"");

					//response.setContentLength((int)new File(tempFile).length());
					IOUtils.copy(new FileInputStream(tempFile),out);
					new File(tempFile).delete();
				}
			}else{
				try {

					String srcTempFile =
							System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + ".pdf";
					FileOutputStream fileIn = new FileOutputStream(srcTempFile);

					IOUtils.copy(in, fileIn);
					fileIn.flush();
					fileIn.close();

					String tempFile =
							System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + ".pdf";
					try(FileOutputStream fileOut = new FileOutputStream(tempFile);FileInputStream fileInputStream=new FileInputStream(srcTempFile)) {
						PdfUtils.waterMarkerText(new PdfReader(fileInputStream), fileOut, waterMark);
					}catch (IOException e){
						e.printStackTrace();
						try(FileInputStream inputStream1=new FileInputStream(srcTempFile)) {
							IOUtils.copy(inputStream1, out);
						}
						return 0;
					}finally {
						new File(srcTempFile).delete();
					}
					if(!packageDownload) {
					  response.addHeader("Content-Length", (int)new File(tempFile).length()+"");
				    }
				  try(FileInputStream fileIn1 = new FileInputStream(tempFile)) {
					  IOUtils.copy(fileIn1,out);
				  }finally {
					new File(tempFile).delete();
				  }
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			out.flush();
			//out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭流
			IOUtils.closeQuietly(in);
//			IOUtils.closeQuietly(out);
		}
		return 0;
	}
}
